<template>
  <div ref="playerRef" v-bind="$attrs"></div>
</template>

<script setup lang="ts">
import {ref, onMounted, watch, nextTick} from 'vue'
import * as AsciinemaPlayer from 'asciinema-player'
import 'asciinema-player/dist/bundle/asciinema-player.css'

const props = defineProps({
  url: [String, Object],
  opts: Object
})

const playerRef = ref()
const player = ref()

watch(() => props.url, () => {
  nextTick(() => {
    createPlayer()
  })
})

const createPlayer = () => {
  if(player.value) {
    player.value.dispose()
  }
  if (!props.url) {
    return
  }
  player.value = AsciinemaPlayer.create(props.url, playerRef.value, {
    speed: 1,
    autoPlay: false,
    fit: false,
    terminalFontSize: '14px',
    theme: 'tango',
    rows: 22,
    ...(props.opts || {})
  })
}

const play = () => {
  player.value.play()
}

const pause = () => {
  player.value.pause()
}

onMounted(() => {
  createPlayer()
})

defineExpose({
  play,
  pause
})

</script>